# _*_ coding: utf-8 _*_
__author__ = 'HaoGe'
from django.views.generic import TemplateView, ListView, DetailView, View
from django.http import JsonResponse
from django.contrib.auth.mixins import LoginRequiredMixin
from confs.views import get_pagerange
from resources.models import ServerUser, NewServer
from django.shortcuts import render_to_response,HttpResponse
from confs.Log import logger

# 主机资源用户展示
class ServerUserListView(LoginRequiredMixin, ListView):
    
    template_name = 'serveruser/serveruser_list.html'
    model = ServerUser
    paginate_by = 10
    ordering = 'id'

    def get_context_data(self, **kwargs):
        context = super(ServerUserListView, self).get_context_data(**kwargs)
        context['page_range'] = get_pagerange(context['page_obj'])
        return context

class ServerUserAPIJsonView(LoginRequiredMixin, ListView):
    def get(self,request):
        jsondata = {
			"code": 0,
			"msg": "",
			"count": 10,
			"data": [
			]
		}
        users = ServerUser.objects.all()
        for s in users:
            hosts = s.serveruser.all()
            host_count = len(hosts)
            m = {"id": s.id,"name":s.name,"username":s.username,"host_count":host_count,"info":s.info}
            jsondata["data"].append(m)

        return JsonResponse(jsondata)

# 主机资源用户创建
class ServerUserCreateView(LoginRequiredMixin, TemplateView):
    template_name = 'serveruser/serveruser_create.html'

    def get(self, request):

        newservers = [{"value": m.id, "name": m.hostname} for m in NewServer.objects.all()]
        jsondata = {"newservers": newservers}

        return JsonResponse(jsondata)

    def post(self, request):
        ret = {'status': 0}
        try:
            server_user = ServerUser.objects.create(
                name=request.POST.get('name'),
                username=request.POST.get('username'),
                password=request.POST.get('password'),
                privatekey=request.POST.get('privatekey'),
                pubkey=request.POST.get('pubkey'),
                info=request.POST.get('info'),
            )
            serveruser_list = request.POST.get('members','').split(',')
            if serveruser_list != ['']:
                for server_id in serveruser_list:
                    server = NewServer.objects.get(id=server_id)
                    server.server_user = server_user
                    server.save()

            ret['msg'] = '创建成功'
        except Exception as e:
            print(e)
            ret['status'] = 1
            ret['msg'] = str(e)

        return JsonResponse(ret)


# 主机资源用户详情信息
class ServerUserDetailView(LoginRequiredMixin, DetailView):
    template_name = 'serveruser/serveruser_detail.html'
    model = ServerUser

    def get(self, request):

        id = request.GET.get('id')
        su = ServerUser.objects.get(id=id)
        servers = NewServer.objects.all()
        data_list = []
        hostid_list = [x.id for x in su.serveruser.all()]
        for s in servers:
            if s.id in hostid_list:
                data_list.append({"name": s.hostname, "value": s.id, "selected": True})
            else:
                data_list.append({"name": s.hostname, "value": s.id})
        jsondata = {"id": su.id,"username":su.username,"name": su.name,"password":su.password,"data_list": data_list,"privatekey":su.privatekey,"pubkey":su.pubkey,"info": su.info}

        return JsonResponse(jsondata)


# 主机资源用户修改
class ServerUserModifyView(LoginRequiredMixin, View):

    def post(self, request):
        ret = {'status': 0}
        if 1 == 1:
            serveruser_id = request.POST.get('id')
            password = request.POST.get('password')
            privatekey = request.POST.get('privatekey')
            pubkey = request.POST.get('pubkey')
            server_id_list = request.POST.get('select').split(',')
            print (pubkey,password,privatekey)
            if password:
                ServerUser.objects.filter(pk=serveruser_id).update(
                    name=request.POST.get('name'),
                    username=request.POST.get('username'),
                    password=password,
                    privatekey = privatekey,
                    pubkey=pubkey,
                    info=request.POST.get('info'),
                )
            else:
                ServerUser.objects.filter(pk=serveruser_id).update(
                    name=request.POST.get('name'),
                    username=request.POST.get('username'),
                    info=request.POST.get('info'),
                    privatekey=request.POST.get('privatekey'),
                    pubkey=request.POST.get('pubkey'),
                )



            serveruser = ServerUser.objects.get(pk=serveruser_id)
            serveruser.serveruser.clear()
            if server_id_list != []:
                for server_id in server_id_list:
                    server = NewServer.objects.get(pk=server_id)
                    server.server_user_id = serveruser_id
                    server.save()
            ret['msg'] = '修改成功'
        #except Exception as e:
        #    ret['status'] = 1
        #    ret['msg'] = str(e)
        return JsonResponse(ret)

class ServerUserDeleteView(LoginRequiredMixin, View):

    def post(self, request):
        ret = {'status': 0}
        try:
            serveruser_id = request.POST.get('serveruser_id')
            serveruser = ServerUser.objects.get(id=serveruser_id)
            serveruser.delete()
            ret['msg'] = '资产用户删除成功'
        except Exception as e:
            ret['status'] = 1
            ret['msg'] = str(e)
        return JsonResponse(ret)